import React, { useEffect, useState, useRef, useContext, useMemo } from "react";
import { Button, Modal, Tooltip, Spin } from "antd";
import { getRandomSliderPosition, drawSlider, drawPic } from "../../utils/canvasDraw";
import Scroll from "./Scroll";
import Context from "./context";
import { LoadingOutlined } from "@ant-design/icons";
import loadingimages from "../../utils/loadingImages";
const imglist = [
  `${process.env.REACT_APP_BASE_URL}/images/f1.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/f2.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/f3.jpg`,
  `${process.env.REACT_APP_BASE_URL}/images/f4.jpg`,
];
const antIcon = <LoadingOutlined style={{ fontSize: 34 }} spin />;
function PinTu({ token }) {
  const { state, dispatch } = useContext(Context);
  const [flager, setFlag] = useState(true);
  const [chax, setChaX] = useState(0);
  // const pianyi = useMemo(() => {
  //   return state.pianyileft * (355 / 386);
  // }, [state.pianyileft]);
  const handleCancel = () => {
    dispatch({ type: "sVisible", value: false });
  };
  const loadBigImgAsync = (url) => {
    // 为了提前加载图片
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const image = new Image();
        image.onload = function () {
          resolve(url);
        };
        image.onerror = function () {
          console.log("图片加载错误");
        };
        image.src = url;
      }, 10);
    });
  };
  const drawCan = function (num) {
    setFlag((prev) => true);
    //  console.log(imglist[num]) ;
    // if(!document.querySelector(".picontainer")) {
    //   return
    // }
    loadBigImgAsync(imglist[num]).then(() => {
      // style={{ left: -chax + pianyi + "px" }}
      window.document.querySelector(".picontainer").innerHTML = `
 <div  id='imgs' style="position:absolute;left:0;background:url(${imglist[num]}) no-repeat;background-size:100% 100%;top:0;width:472px;height:236px" />
 <canvas width="472" height="236" class="back" ></canvas>
 <canvas
   width="472"
   height="236"
   class="front"
 ></canvas> <div class='error'>请您正确拼接图案！</div>
 <div class='success'>您正确拼接了图案,真厉害！！！</div>`;
      let ctx1 = window.document.querySelector(".back").getContext("2d");
      let ctx2 = window.document.querySelector(".front").getContext("2d");
      // ctx2.drawImage(document.getElementById('imgs'),0,0,472,236)
      // ctx1.drawImage(document.getElementById('imgs'),0,0,472,236)
      drawPic(ctx2, 472, 236, imglist[num]);
      // drawPic(ctx2,472, 236,imglist[num] );
      ctx1.beginPath();
      ctx1.strokeStyle = "rgba(0,0,0,0)";
      // ctx1.fillStyle='transparent' ;
      // ctx2.fillStyle='transparent' ;
      let l = 60;
      let r = 20;
      let L = l + r * 2 - 20;
      // 一般拼图都在右边
      let x = getRandomSliderPosition(150, 472 - L - 20);
      let y = getRandomSliderPosition(2 * r + 10, 236 - L - 20);
      drawSlider(ctx1, x, y, "fill", l, r);
      drawSlider(ctx2, x, y, "clip", l, r);
      let cha = x - 15;
      setChaX(() => cha);
      dispatch({ type: "xTrue", value: cha });
      document.querySelector(".front").style.left = -cha + "px";
      setTimeout(() => {
        setFlag((prev) => false);
      }, 200);
    });
  };
  useEffect(() => {
    // 初始化话得到的验证值都是undefined
    if (state.visible) {
      setTimeout(() => {
        drawCan(0);
        //   dispatch({ type: "sFront", ele: front });
        // dispatch({ type: "sFront", ele: front });
      }, 0);
    }
    return () => {};
  }, [state.visible]);
  return (
    <Modal
      centered={true}
      closable={false}
      className="loginModal"
      title="拼图校验"
      visible={state.visible}
      maskClosable={false}
      onCancel={handleCancel}
      footer={[
        <Button key="back" type="primary" onClick={handleCancel}>
          返回登录
        </Button>,
      ]}
    >
      <div className="picCanvas">
        <div className="picontainer">
          {/* <canvas width="472" height="236" className="back" ref={back}></canvas>
          <canvas
            width="472"
            height="236"
            className="front"
            style={{ left: -chax + pianyi + "px" }}
            ref={front}
          ></canvas> */}
        </div>
        {flager ? (
          <div
            className="outerpaincontainer"
            style={{
              overflow: "hidden",
              width: "472px",
              height: "236px",
              marginTop: "-246px",
              marginBottom: "10px",
              backgroundColor: "#e5e5e5",
              position: "relative",
            }}
          >
            <div
              style={{
                position: "absolute",
                left: "50%",
                top: "50%",
                marginLeft: "-17px",
                width: "34px",
                marginTop: "-13px",
              }}
            >
              <div
                style={{
                  backgroundImage: `url(/images/prephoto.png)`,
                  backgroundRepeat: "no-repeat",
                  width: "34px",
                  height: "26px",
                  backgroundSize: "164.70588%",
                  backgroundPosition: "0 27.22513%",
                  marginBottom: "10px",
                }}
              ></div>
              <Spin indicator={antIcon}></Spin>
            </div>
          </div>
        ) : null}

        <Tooltip title="刷新拼图">
          <Button
            title="刷新图片"
            type="primary"
            shape="circle"
            onClick={() => {
              drawCan(parseInt(Math.random() * imglist.length));
            }}
            icon={<span className="iconfont icon-shuaxin1"></span>}
            size="small"
          />
        </Tooltip>
      </div>
      <Scroll token={token} flager={flager}></Scroll>
    </Modal>
  );
}

export default PinTu;
